<template>
  <a-form
    ref="stepForm4Ref"
    :model="formData"
    layout="vertical"
    :wrapperCol="{ span: 24 }"
    labelAlign="left"
    :hideRequiredMark="false"
    :rules="rules"
    :scrollToFirstError="true"
    style="margin-top: 20px"
  >
    <a-col :span="24">
      <a-form-item name="isAllocation">
        <template #label>
          <span>是否限制可派发机构</span>
        </template>
        <a-radio-group
          v-model:value="formData['isAllocation']"
          :disabled="props.isDisabled"
        >
          <a-radio :value="0">否</a-radio>
          <a-radio :value="1">是</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-col>
    <div v-if="formData['isAllocation'] === 1">
      <a-col :span="24">
        <a-form-item label="渠道码是否可见" name="isChannelDisplay">
          <a-radio-group
            v-model:value="formData['isChannelDisplay']"
            :disabled="props.isDisabled"
          >
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-tabs v-model:activeKey="activeKey" style="margin-top: 20px;">
        <a-tab-pane key="1" :disabled="props.isDetail">
          <template #tab>
            <span>单个机构分配</span>
          </template>
        </a-tab-pane>
        <a-tab-pane v-if="!props.isPush" key="2" :disabled="props.isDetail">
          <template #tab>
            <span>多个机构分配</span>
          </template>
        </a-tab-pane>
      </a-tabs>

      <a-row type="flex" justify="space-between" wrap="true">
        <a-row v-if="activeKey === '1'" style="margin:20px 0 30px;">
          <a-col :span="10">
            <a-tree-select
              v-model:value="formData['agentNo']"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              :treeDefaultExpandAll="false"
              placeholder="请选择机构"
              :disabled="props.isDetail"
            />
          </a-col>
          <a-col :span="6">
            <a-input
              v-model:value="formData['agentNumber']"
              placeholder="请输入数量"
              allowClear
              oninput="value=value.replace(/[^\d]/g,'')"
              :disabled="props.isDetail"
            />
          </a-col>
          <a-col :span="4" style="padding: 0 20px">
            <a-button
              type="primary"
              :disabled="props.isDetail"
              style="padding: 0 20px"
              @click="handleAddMch"
            >
              新增
            </a-button>
          </a-col>
        </a-row>

        <a-col v-if="activeKey === '2'" :span="24">
          <a-form-item name="fileList">
            <template #label>
              <span style="margin-right: 20px">文件上传</span>
              <a-button
                class="item"
                type="link"
                style="padding: 4px 0"  
                href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/template/import_agent_template.xlsx"
              >
                下载可分配机构模板
              </a-button>
            </template>
            <a-upload-dragger
              v-model:fileList="formData['fileList']"
              :action="uploadAction"
              :data="uploadParams"
              :maxCount="1"
              accept=".xlsx, .xls"
              name="file"
              :beforeUpload="beforeUpload"
              :disabled="props.isDisabled"
              @change="uploadChange"
            >
              <p class="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
              <p class="ant-upload-hint">
                <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
              </p>
            </a-upload-dragger>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item name="mchList" label="可分配机构清单">
            <page-header-wrapper>
              <a-card class="table-card">
                <GzSearchForm 
                  :searchFunc="handleSearch" 
                  :resetFunc="handleReset" 
                  searchConditionNum="6"
                >
                  <gz-text-up
                    v-model:value="searchParams.agentNo"
                    placeholder="机构号"
                    style="width: 200px"
                  />
                  <gz-text-up
                    v-model:value="searchParams.agentName"
                    placeholder="机构名称"
                    style="width: 200px"
                  />
                </GzSearchForm>
                <GzTable
                  ref="tableRef"
                  :table-columns="tableColumns"
                  :init-data="true"
                  :req-table-data-func="fetchTableData"
                  :search-data="searchParams"
                  :scrollX="600"
                  rowKey="agentNo"
                  size="small"
                >
                  <template #topBtnSlot>
                    <a-button type="primary" :disabled="props.isDetail" @click="handleDeleteAll">删除所有派发机构</a-button>
                  </template>
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key == 'isChannelDisplay'">
                      <GzTableColState :state="record.isChannelDisplay" :disabled="props.isDetail" :show-switch-type="$access('ENT_SCORE_RULE_INFO_EDIT')" :on-change="(isChannelDisplay) => { return stateChangeFunc(record.awardAgentId, isChannelDisplay)}" />
                    </template>

                    <template v-if="column.key === 'operation'">
                      <a-button
                        type="link"
                        danger
                        :disabled="props.isDetail"
                        @click="handleDelete(record)"
                      >
                        删除
                      </a-button>
                    </template>
                  </template>
                </GzTable>
              </a-card>
            </page-header-wrapper>
          </a-form-item>
        </a-col>
      </a-row>
    </div>
  </a-form>
</template>

<script setup>
import { ref, reactive, onMounted,getCurrentInstance,nextTick} from 'vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
// import {$apiAgentInfo} from '@/api/components/GzTreeSelect/index'
import{$addAgentOrg,$getActivityAwardAgentList,$deleteAllActivityAwardAgent,$deleteActivityAwardAgent,$uploadActivityAwardAgent,$updateActivityAwardAgentState,$queryOrgTree,$configAllocation}from '@/api/awardMange/coupon/index'
import {$getUploadFormParams} from '@/api/components/GzUpload/index'
const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

// 定义props
const props = defineProps({
  // 奖品id
    awardId: {
    type: String,
    default:'',
  },
  // 奖品类型
  awardType: {
    awardType: Number,
    default:0,
  },
    isAllocation:{
    type: Number,
    default:0,
  },
  // 机构号
  agentNo: {
    type: String,
    default:'',
  },
  // 查看详情
  isDisabled:{
    type:Boolean,
    default:false
  },
  isDetail:{
    type:Boolean,
    default:false
  },
  // 是否追加
  isPush: {
    type: Boolean,
    default: false,
  }

})

// const emit = defineEmits(['update:modelValue', 'add-merchant', 'delete-merchant', 'delete-all', 'upload-success', 'upload-error','before-upload'])
  
const formData = ref({
  ossFileUrl:'',
  isAllocation: props.isAllocation, // 是否限制员工
  isChannelDisplay:1,
  agentNo: null,
}) 
console.log('props.isAllocation',props.isAllocation)

// 表单引用
const stepForm4Ref = ref()
// 表格引用
const tableRef = ref()

// 当前激活的tab
const activeKey = ref('1')

// 搜索参数
const searchParams = reactive({
  agentNo: null,
  agentName: null
})
const uploadAction = ref()
const uploadParams = ref()

// 可核销商户表格
const tableColumns = [
  { title: '机构号', dataIndex: 'agentNo', key: 'agentNo' },
  { title: '机构名称', dataIndex: 'agentName', key: 'agentName' },
  { title: '已分配下级数量', dataIndex: 'numAllocation', key: 'numAllocation' },
  { title: '已派发数量', dataIndex: 'numConsume', key: 'numConsume' },
  { title: '总数量', dataIndex: 'num', key: 'num' },
  { title: '渠道码可见是否开启', dataIndex: 'isChannelDisplay', key: 'isChannelDisplay', align: 'center' },
  { title: '操作', dataIndex: 'operation', key: 'operation', align: 'center' },
]

const rules = ref(
  {
      mchList: [{ required: true, trigger: 'blur', validator: mchListValidator }],
      isChannelDisplay:[{ required: true, message: '', trigger: 'change' }]
  }
)
// 是否存在可核销商户
const hasMch = ref(false)
/** 可核销商户上传校验 */
function mchListValidator() {
  if (hasMch.value) {
    // 存在可核销商户
    return Promise.resolve()
  } else {
    return Promise.reject('请上传可核销商户清单')
  }
}
  
// 请求table接口数据
function fetchTableData(params) {
  return new Promise((resolve) => {
    $getActivityAwardAgentList({
        ...params,
        awardId: props.awardId,
        awardType:props.awardType,
      })
      .then((res) => {
        hasMch.value = res.records.length
        resolve(res)
      })
  })
}

function stateChangeFunc(awardAgentId,isChannelDisplay){
  $updateActivityAwardAgentState({awardAgentId,isChannelDisplay}).then(res => { 
       $infoBox.message.success('修改成功')
       tableRef.value.refTable(false)
 })
}
// 添加派发机构
const handleAddMch = () => {

  
  if (!formData.value.agentNo) {
    message.warning('请选择机构')
    return
  }
  if (!formData.value.agentNumber) {
    message.warning('请输入数量')
    return
  }

  
 $addAgentOrg( {
      awardId: props.awardId,
      agentNo: formData.value.agentNo,
      num: Number(formData.value.agentNumber),
      awardType:props.awardType,
      isChannelDisplay:formData.value.isChannelDisplay
    })
    .then((res) => {
      formData.value.agentNumber = ''
        formData.value.isChannelDisplay=1
      nextTick(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('新增成功')
      })
    })
}

// 删除商户
const handleDelete = (record) => {
    $infoBox.confirmDanger('确认删除？', '请确认是否删除当前可核销商户？', () => {
    $deleteActivityAwardAgent({ awardAgentId: record.awardAgentId })
      .then(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
  })
}

// 删除所有商户
const handleDeleteAll = () => {
 
  $infoBox.confirmDanger('确认删除？', '请确认是否删除所有可核销商户？', () => {
    $deleteAllActivityAwardAgent( { awardId:props.awardId,awardType:props.awardType})
      .then(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
  })
}

// 搜索
const handleSearch = () => {
  
  tableRef.value.refTable(true)

}

// 重置搜索
const handleReset = () => {
  searchParams.agentNo = null
  searchParams.agentName = null
  tableRef.value.refTable(true)
}

/**
 * 文件上传
 */
 function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'activity').then((res) => {
    uploadAction.value = res.formActionUrl // action
    uploadParams.value= res.formParams //表单组件
    formData.value.ossFileUrl = res.ossFileUrl
  })
}

// 上传状态改变
const uploadChange = (info) => {  
 if (info.file.status === 'error') {
    // 上传异常
   formData.value.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }
  if (info.file.status === 'done') {
   $uploadActivityAwardAgent( {
      awardId: props.awardId,
      ossFileUrl: formData.value.ossFileUrl,
      awardType:props.awardType,
    })
    .then((res) => {
      tableRef.value.refTable(true)
      $infoBox.message.success('导入成功')
    })
  }
}

function validate (){
  return stepForm4Ref.value.validate()
}

const treeData = ref([])

// 机构树数据
function getProxyList() {
  return $queryOrgTree({agentNo:props.agentNo}).then((res) => {    
    treeData.value = [{
      id: res.agentNo,
      value: res.agentNo,
      agentNo: res.agentNo,
      title: res.agentName,
      agentName: res.agentName,
      level: res.level,
      disabled: false,
      key: res.agentNo,
      children: res.children.map(item => ({
        id: item.agentNo,
        value: item.agentNo,
        agentNo: item.agentNo,
        title: item.agentName,
        agentName: item.agentName,
        level: item.level,
        disabled: false,
        key: item.agentNo,
        children: item.children ? item.children.map(child => ({
          key: child.agentNo,
          id: child.agentNo,
          value: child.agentNo,
          agentNo: child.agentNo,
          title: child.agentName,
          agentName: child.agentName,
          level: child.level,
          disabled: false,
        })) : [],
      }))
    }]
  })
}
// 更新是否限限制机构状态
const handleIsAllocationChange = () => {
  return $configAllocation({
              awardId:props.awardId,
              isAllocation:formData.value.isAllocation,
              awardType:props.awardType,
            }).then(res=>{

            })
}
  onMounted(() => {
   getProxyList()
   
  })
defineExpose({
 validate,
 handleIsAllocationChange,
})
</script>

<style lang="less" scoped>
.table-card {
  margin-top: 20px;
}
::v-deep(.ant-select) {
  width: 200px !important;
}
:deep(.table-layer .table-search-item) {
  width: calc(100% / 3);
}
</style>